import { Injectable, NotFoundException, ForbiddenException, ConflictException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Project } from './project.entity';
import { CreateProjectDto } from './dto/create-project.dto';
import { UpdateProjectDto } from './dto/update-project.dto';
import { User } from '../user/user.entity';
import { FieldType } from '../form-config/field-type.entity';

@Injectable()
export class ProjectService {
  constructor(
    @InjectRepository(Project)
    private projectRepository: Repository<Project>,
    @InjectRepository(FieldType)
    private fieldTypeRepository: Repository<FieldType>,
  ) {}

  async create(createProjectDto: CreateProjectDto, owner: User): Promise<Project> {
    // 检查项目名称是否已存在
    const existingProject = await this.projectRepository.findOne({
      where: { name: createProjectDto.name },
    });

    if (existingProject) {
      throw new ConflictException('Project name already exists');
    }

    const project = this.projectRepository.create({
      ...createProjectDto,
      owner,
    });

    // 如果提供了字段类型ID，则关联字段类型
    if (createProjectDto.fieldTypeIds && createProjectDto.fieldTypeIds.length > 0) {
      const fieldTypes = await this.fieldTypeRepository.findByIds(createProjectDto.fieldTypeIds);
      project.fieldTypes = fieldTypes;
    }

    return await this.projectRepository.save(project);
  }

  async findOne(id: number): Promise<Project> {
    const project = await this.projectRepository.findOne({
      where: { id },
      relations: ['owner', 'fieldTypes', 'formConfig', 'formConfig.fieldTypes'],
    });

    if (!project) {
      throw new NotFoundException(`Project with ID ${id} not found`);
    }

    return project;
  }

  async findAll(): Promise<Project[]> {
    return await this.projectRepository.find({
      relations: ['owner', 'fieldTypes'],
    });
  }

  async findProjectsByUser(user: User): Promise<Project[]> {
    return await this.projectRepository.find({
      where: { owner: { id: user.id } },
      relations: ['fieldTypes'],
    });
  }

  async update(id: number, updateProjectDto: UpdateProjectDto, user: User): Promise<Project> {
    // 查找项目
    const project = await this.projectRepository.findOne({
      where: { id },
      relations: ['owner', 'fieldTypes'],
    });

    if (!project) {
      throw new NotFoundException(`Project with ID ${id} not found`);
    }

    // 检查权限：只有最高级管理员（level 1）可以更新项目
    if (user.level !== 1) {
      throw new ForbiddenException('Only top-level administrators can update projects');
    }

    // 如果要更新名称，检查名称是否已被其他项目使用
    if (updateProjectDto.name && updateProjectDto.name !== project.name) {
      const existingProject = await this.projectRepository.findOne({
        where: { name: updateProjectDto.name },
      });

      if (existingProject && existingProject.id !== id) {
        throw new ConflictException('Project name already exists');
      }
    }

    // 更新基本信息
    if (updateProjectDto.name) {
      project.name = updateProjectDto.name;
    }
    if (updateProjectDto.description !== undefined) {
      project.description = updateProjectDto.description;
    }
    if (updateProjectDto.mainImage !== undefined) {
      project.mainImage = updateProjectDto.mainImage;
    }

    // 更新字段类型关联
    if (updateProjectDto.fieldTypeIds !== undefined) {
      if (updateProjectDto.fieldTypeIds.length > 0) {
        const fieldTypes = await this.fieldTypeRepository.findByIds(updateProjectDto.fieldTypeIds);
        project.fieldTypes = fieldTypes;
      } else {
        project.fieldTypes = [];
      }
    }

    return await this.projectRepository.save(project);
  }
}